package cn.apestar.common.office.eneity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.io.FileUtils;
import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.GetPolicy;
import com.qiniu.api.rs.PutPolicy;
import com.qiniu.api.rs.URLUtils;
import cn.apestar.common.config.Global;

/**
 * 转化图片参数 标题、简要说明. <br>
 * 类详细说明.
 * <p>
 * Copyright: Copyright (c) 2016年4月6日 上午10:57:18
 * <p>
 * 
 * @author lvh
 * @version 1.0.0
 */
public class OfficeEntity {

    /**
     * 返回PDF信息
     */
    public String officeCovertPdfUrl = "{pdfUrl}?odconv/pdf";

    public String getPdfUrl() {

        return pdfUrl;
    }

    public void setPdfUrl(String pdfUrl) {

        this.pdfUrl = pdfUrl;
    }

    public String pdfUrl;

    public String savePdfUrl(String id) {

        String pdfCovertImageUrl = officeCovertPdfUrl.replace("{pdfUrl}", getPdfUrl());
        try {
            String projectPath = download(pdfCovertImageUrl, id);

            Mac mac = new Mac(Global.getConfig("qiniu_access_key"), Global.getConfig("qiniu_secret_key"));
            // 请确保该bucket已经存在
            PutPolicy putPolicy = new PutPolicy(Global.getConfig("qiniu_bucket_name"));
            String uptoken = putPolicy.token(mac);
            PutExtra extra = new PutExtra();
            String key = System.currentTimeMillis() + id;
            File file = new File(projectPath);
            PutRet ret = IoApi.putFile(uptoken, key, new File(projectPath), extra);
            String address = getQiniuFileUrl(Global.getConfig("qiniu_domain"), ret.getKey());
            FileUtils.forceDeleteOnExit(file);
            return address;

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 下载七牛云
     * 
     * @return
     * @throws EncoderException
     * @throws AuthException
     */
    public String getQiniuFileUrl(String demain, String key) throws EncoderException, AuthException {

        Mac mac = new Mac(Global.getConfig("qiniu_access_key"), Global.getConfig("qiniu_secret_key"));
        String baseUrl = URLUtils.makeBaseUrl(demain, key);
        GetPolicy getPolicy = new GetPolicy();
        String downloadUrl = getPolicy.makeRequest(baseUrl, mac);
        // downloadUrl = URLEncoder.encode(downloadUrl);
        return downloadUrl;
    }

    /**
     * 下载文件到本地
     *
     * @param urlString
     *            被下载的文件地址
     * @param filename
     *            本地文件名
     * @return
     * @throws Exception
     *             各种异常
     */
    public static String download(String urlString, String filename) throws Exception {

        File file = new File(Global.getConfig("projectImagePath"));
        if (!file.exists()) {
            file.mkdirs();
        }
        String projectImagePath = Global.getConfig("projectImagePath") + "\\" + filename + ".pdf";
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        OutputStream os = new FileOutputStream(projectImagePath);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕，关闭所有链接
        os.close();
        is.close();
        return projectImagePath;
    }

}
